﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Cofe.Core;
using Cofe.Web.Utils;

namespace Cofe.Web.Feed
{
    public enum FeedType { RecentEventFeed, ArchiveFeed }

    public class FeedId
    {
        public static FeedId Initial = FeedId.FromId(1, FeedType.RecentEventFeed);

        public FeedType FeedType { get; set; }
        public FeedDirectory FeedDirectory
        {
            get
            {
                switch (FeedType)
                {
                    case Feed.FeedType.RecentEventFeed: return FeedDirectory.Current;
                    case Feed.FeedType.ArchiveFeed: return FeedDirectory.Archive;
                    default: throw new NotSupportedException();
                }
            }
        }
        public int Id { get; set; }
        public string FileName { get; set; }       
        
        public static FeedId FromUrl(Uri uri, string fileName, IFeedBuilder feedBuilder)
        {
            Int32 id = 1;
            Int32.TryParse(new Regex("page=(?<page>(\\d)*)").Match(uri.OriginalString).Groups["page"].Value, out id);                         
            return new FeedId()
            {
                Id = id,
                FileName = fileName,
                FeedType = FeedType.RecentEventFeed
            };
        }


        //public static FeedId FromId(int id, string fileName)
        //{
        //    if (fileName == null)
        //        fileName = id.ToString() + ".atom";
        //    else
        //        if (PathFE.GetExtension(fileName) != ".atom")
        //            throw new ArgumentException("Filename must end with .atom");

        //    return new FeedId()
        //    {
        //        Id = id,
        //        FileName = fileName, 
        //        FeedType = FeedType.RecentEventFeed
        //    };
        //}


        public static FeedId FromId(int id, FeedType feedType)
        {
            string fileName = feedType == FeedType.ArchiveFeed ? 
                 id + ".atom" :
                Guid.NewGuid().ToString() + ".atom";
            return new FeedId()
            {
                Id = id,
                FileName = fileName,
                FeedType = feedType
            };
        }

        
        public FeedId Next()
        {
            return FeedId.FromId(Id + 1, Feed.FeedType.RecentEventFeed);
        }

        public FeedId ToArchive()
        {
            if (this.FeedType == FeedType.ArchiveFeed)
                throw new InvalidOperationException();
            return FromId(this.Id, Feed.FeedType.ArchiveFeed);
        }


     


       
    }
}
